<template>
  <div id="bg">
    <div id="activiy-form">
      <h1 class="font-bold">活动邀约</h1>
      <IForm
        :list="list"
        :submit-text="'我要预约'"
        :handleGetMsger="getMsger"
        :model-value="formValue"
        @submit="handleFormSubmit"
      />
    </div>
  </div>
</template>
  
<script setup name="WorkbenchPage">
import { ref, reactive, onBeforeMount } from 'vue'
import { useRouter } from 'vue-router'
import { getDealers, getModelList } from '@/api/activity/index'
import { login, smsSend } from '@/api/system/index'
import { showToast } from 'vant'
const hasDealer = ref(false)
let dealers = []
// 引入路由
const router = useRouter()
// 引入路由
const route = useRoute()

const getMsger = async (formData) => {
  return new Promise(async (resolve, reject) => {
    // 检查手机号格式是否正确
    const mobileReg = /^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/
    if (!mobileReg.test(formData.phone)) {
      showToast('请输入正确的手机号')
      return false
    }
    const res = await smsSend({
      mobile: formData.phone
    })
    if (res.code === 200) {
      showToast('发送成功')
      resolve(true)
      return true
    } else {
      showToast('发送失败')
      resolve(false)
      return false
    }
  })

  /*  */
}
const list = ref([
  {
    type: 'input',
    label: '',
    model: 'name',
    placeholder: '请输入姓名',
    rules: [{ required: true, message: '请输入姓名' }]
  },
  {
    type: 'input',
    label: '',
    model: 'phone',
    placeholder: '请输入手机号',
    rules: [{ required: true, message: '请输入手机号' }]
  },
  {
    type: 'msger',
    label: '',
    model: 'code',
    placeholder: '请输入验证码',
    rules: [{ required: true, message: '请输入验证码' }]
  },
  {
    type: 'select',
    label: '',
    model: 'dealerId',
    placeholder: '请选择经销商',
    options: [],
    rules: [{ message: '请选择经销商' }]
  },
  {
    type: 'select',
    label: '',
    model: 'modelId',
    placeholder: '请选择车型',
    options: [],
    rules: [{ message: '请选择车型' }]
  }
])

// 表单默认值
const formValue = reactive({
  name: '',
  phone: '',
  code: '',
  dealerId: 0,
  modelId: 1
})

// 处理表单提交
const handleFormSubmit = async (formData) => {
  const commitData = {
    name: formData.name,
    phone: formData.phone,
    code: formData.code
  }
  if (route.query.dealer) {
    commitData.dealerId = formData.dealerId
    commitData.dealerSelected = true
  } else {
    // 从dealers数组中随机取一个经销商
    const randomIndex = Math.floor(Math.random() * dealers.length)
    commitData.dealerId = dealers[randomIndex].value
    formData.dealerId = commitData.dealerId
    commitData.dealerSelected = false
  }

  if (formData.modelId) {
    commitData.modelId = formData.modelId
  }
  console.log(commitData, '-----commitData--------')
  const res = await login(commitData)
  if (res.code === 200) {
    commitData.dealer = dealers.find(
      (item) => item.value === formData.dealerId
    ).label
   
    localStorage.setItem('userInfo', JSON.stringify(commitData))
    setTimeout(() => {
      router.push({
        name: 'dated',
        query: {
          phone: formData.phone
        }
      })
    }, 300)
  } else {
    showToast(res.msg)
  }
}

// 初始化
const init = async () => {
  const LuserInfo = localStorage.getItem('userInfo')
  if (LuserInfo !== null) {
    if (JSON.parse(LuserInfo).phone) {
      router.push({
        name: 'dated',
        query: {
          phone: JSON.parse(LuserInfo).phone
        }
      })
      return false
    }
  }
  const res = await getDealers({
    pageNum: 1,
    pageSize: 100
  })
  if (res.code === 200) {
    dealers = res.data.records.map((item) => {
      return {
        label: item.name,
        value: item.id
      }
    })
    list.value[3].options = dealers
  } else {
    showToast(res.msg)
  }

  const modelRes = await getModelList()
  if (modelRes.code === 200) {
    list.value[list.value.findIndex((e) => e.model == 'modelId')].options = modelRes.data.map(
      (item) => {
        return {
          label: item.name,
          value: item.id
        }
      }
    )
  } else {
    showToast(res.msg)
  }
}
onBeforeMount(() => {
  if (!route.query.dealer) {
    hasDealer.value = true
    list.value.splice(3, 1)
  }
})
onMounted(() => {
  init()
})
</script>
  
<style lang="less">
body {
  background-size: 100% auto;
}
#bg {
  position: relative;
  width: 100vw;
  max-width: 480px;
  margin: 0 auto;
  height: 100vh;
  background: url(../../assets/img/c_bg_less.png);
  background-size: 100% auto;
}
#activiy-form {
  position: absolute;
  bottom: 0;
  box-sizing: border-box;
  width: 100%;
  padding: 0 40px 30px 40px;
  /* 添加毛玻璃效果 */
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px); /* Safari 兼容 */
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 0;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 1);
  h1 {
    font-size: 28px;
    text-align: center;
    padding: 25px 0 10px 0;
    color: #fff;
  }
}
</style>